﻿using Autofac.Features.Metadata;
using Models;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;

using wnet.admin.Models.dto;
using ZR.Common;
using ZR.Model.System;
using ZR.Model.System.Vo;

using System.IO;
using wnet.admin.wentcommon;
using System.Configuration;





namespace wnet.admin.Controllers.pcapi
{

    public class sysloginController : ApiController
    {

        private readonly ISqlSugarClient _sqlSugarClient;
        public sysloginController()
        {
            _sqlSugarClient = SqlSugarConfig.CreateClient();
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("login")]
        public object login(logindto entity)
        {

            List<object> list = new List<object>();


            string Password = tools.GetMD5Hash(entity.password);
            var user = _sqlSugarClient.Queryable<SysUser>().Where(q => q.Password == entity.password && q.UserName == entity.username).First();
            if (user == null)
            {
                return new { code = 105, msg = "賬號密碼錯誤", data = "错误" };
            }

            string token = tools.Gettoken(user.UserId.ToString());
            return new { code = 200, msg = "成功", data = token };

            //return new { code = 200, msg = "成功", data = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkJlYXJlciJ9.eyJwcmltYXJ5c2lkIjoiMSIsInVuaXF1ZV9uYW1lIjoiYWRtaW4iLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3VzZXJkYXRhIjoie1wiVXNlcklkXCI6MSxcIkRlcHRJZFwiOjAsXCJVc2VyTmFtZVwiOlwiYWRtaW5cIixcIlJvbGVJZHNcIjpbXCJhZG1pblwiXSxcIlJvbGVzXCI6W3tcIlJvbGVJZFwiOjEsXCJSb2xlS2V5XCI6XCJhZG1pblwiLFwiRGF0YVNjb3BlXCI6MX1dLFwiRXhwaXJlVGltZVwiOlwiMDAwMS0wMS0wMVQwMDowMDowMFwifSIsIkF1ZGllbmNlIjoieXN4aWVodWlkZW1vLk5FVCIsIklzc3VlciI6InlzeGllaHVpZGVtby5ORVQiLCJuYmYiOjE3MTg3MjQyNjksImV4cCI6MTcxOTU4ODI2OSwiaWF0IjoxNzE4NzI0MjY5LCJpc3MiOiJ5c3hpZWh1aWRlbW8uTkVUIiwiYXVkIjoieXN4aWVodWlkZW1vLk5FVCJ9.CP3kYouDLsxkuuDzFBs7mBb_3szD8ngvdkKW8o7dfps" };


        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("LogOut")]
        public object LogOut(logindto entity)
        {

            List<object> list = new List<object>();

            return new { code = 200, msg = "成功", data = "退出成功" };
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("captchaImage")]
        public object captchaImage(logindto entity)
        {

            List<object> list = new List<object>();

            return new { code = 200, msg = "成功", data = "成功" };
        }

        [TokenAuth]
        [HttpGet]
        [Route("getInfo")]
        public object getInfo()
        {


            var user = _sqlSugarClient.Queryable<SysUser>().Where(q => q.UserId == 1).First();


            //前端校验按钮权限使用
            //角色集合 eg: admin,yunying,common
            List<string> roles = new List<string>();
            roles.Add("admin");
            //权限集合 eg *:*:*,system:user:list
            List<string> permissions = new List<string> { "*:*:*" };

            return new { code = 200, msg = "成功", data = new { user, roles, permissions } };
        }
       

        /// <summary>
        /// 获取路由信息
        /// </summary>
        /// <returns></returns> 
        [TokenAuth]
        [HttpGet]
        [Route("business/adminlogingetRouters")]
        public object GetRouters2()
        {
            var menus = SelectTreeMenuList();

            //return SUCCESS(BuildMenus(menus));
            var data = new { code = 200, msg = "成功", data = BuildMenus(menus) };

            return Json(data, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
        }

        /// <summary>
        /// 获取路由信息
        /// </summary>
        /// <returns></returns> 
        [TokenAuth]
        [HttpGet]
        [Route("getRouters")]
        public object GetRouters()
        {
            var menus = SelectTreeMenuList();

            //return SUCCESS(BuildMenus(menus));
            var data = new { code = 200, msg = "成功", data = BuildMenus(menus) };

            return Json(data, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
        }

        //system/CommonLang/list/zh-cn

       
        [HttpGet]
        [Route("system/CommonLang/list/zh-cn")]
        public object langlist()
        {
            List<string> permissions = new List<string>();
            return new { code = 200, msg = "成功", data = new { } };
        }
       
        [HttpGet]
        [Route("system/CommonLang/list/zh-tw")]
        public object langlisttw()
        {
            List<string> permissions = new List<string>();
            return new { code = 200, msg = "成功", data = new { } };
        }

        /// <summary>
        /// 获取所有菜单（菜单管理）
        /// </summary>
        /// <returns></returns>
          List<SysMenu> SelectTreeMenuList()
        {
            string MenuTypeIdArr = "M,C";


            List<long> ints = new List<long>();
            ints.Add(1123);
            ints.Add(1124);
            ints.Add(1125);
            ints.Add(1126);
            ints.Add(1127);
    
      
            var list = _sqlSugarClient.Queryable<SysMenu>()

                .Where(it => it.Status == "0")
                .Where(it => MenuTypeIdArr.Contains(it.MenuType) && ints.Contains(it.MenuId))

                .OrderBy(it => new { it.ParentId, it.OrderNum })
                .ToTree(it => it.Children, it => it.ParentId, 0);

            return list;
        }
        /// <summary>
        /// 获取路由侧边栏,动态生成
        /// </summary>
        /// <param name="menus"></param>
        /// <returns></returns>
          List<RouterVo> BuildMenus(List<SysMenu> menus)
        {
            List<RouterVo> routers = new List<RouterVo>();
            if (menus == null) return routers;

            foreach (var menu in menus)
            {
                RouterVo router = new RouterVo()
                {
                    Hidden = "1".Equals(menu.Visible),
                    Name = GetRouteName(menu),
                    Path = GetRoutePath(menu),
                    Component = GetComponent(menu),
                    Meta = new Meta(menu.MenuName, menu.Icon, "1".Equals(menu.IsCache), menu.MenuNameKey, menu.Path, menu.Create_time)
                };

                List<SysMenu> cMenus = menu.Children;
                //是目录并且有子菜单
                if (cMenus != null && cMenus.Count > 0 && UserConstants.TYPE_DIR.Equals(menu.MenuType))
                {
                    router.AlwaysShow = true;
                    router.Redirect = "noRedirect";
                    router.Children = BuildMenus(cMenus);
                }
                else if (IsMeunFrame(menu))
                {
                    router.Meta = null;
                    List<RouterVo> childrenList = new List<RouterVo>();
                    RouterVo children = new RouterVo()
                    {
                        Path = menu.Path,
                        Component = menu.Component,
                        Name = string.IsNullOrEmpty(menu.Path) ? "" : menu.Path.ToLower(),
                        Meta = new Meta(menu.MenuName, menu.Icon, "1".Equals(menu.IsCache), menu.MenuNameKey, menu.Path, menu.Create_time)
                    };
                    childrenList.Add(children);
                    router.Children = childrenList;
                }
                else if (menu.ParentId == 0 && IsInnerLink(menu))
                {
                    router.Meta = new Meta(menu.MenuName, menu.Icon);
                    router.Path = "/";
                    List<RouterVo> childrenList = new List<RouterVo>();
                    RouterVo children = new RouterVo();
                    string routerPath = InnerLinkReplaceEach(menu.Path);
                    children.Path = routerPath;
                    children.Component = UserConstants.INNER_LINK;
                    children.Name = routerPath.ToLower();
                    children.Meta = new Meta(menu.MenuName, menu.Icon, menu.Path);
                    childrenList.Add(children);
                    router.Children = childrenList;
                }
                routers.Add(router);
            }

            return routers;
        }


        /// <summary>
        /// 获取路由名称
        /// </summary>
        /// <param name="menu">菜单信息</param>
        /// <returns>路由名称</returns>
          string GetRouteName(SysMenu menu)
        {
            string routerName = menu.Path.ToLower();
            // 非外链并且是一级目录（类型为目录）
            if (IsMeunFrame(menu))
            {
                routerName = string.Empty;
            }
            return routerName;
        }

        /// <summary>
        /// 获取路由路径
        /// </summary>
        /// <param name="menu">菜单信息</param>
        /// <returns>路由地址</returns>
          string GetRoutePath(SysMenu menu)
        {
            string routerPath = menu.Path;
            // 内链打开外网方式
            if (menu.ParentId != 0 && IsInnerLink(menu))
            {
                routerPath = InnerLinkReplaceEach(routerPath);
            }
            // 非外链并且是一级目录（类型为目录）
            if (0 == menu.ParentId && UserConstants.TYPE_DIR.Equals(menu.MenuType)
                && UserConstants.NO_FRAME.Equals(menu.IsFrame))
            {
                routerPath = "/" + menu.Path;
            }
            else if (IsMeunFrame(menu))// 非外链并且是一级目录（类型为菜单）
            {
                routerPath = "/";
            }
            return routerPath;
        }

        /// <summary>
        /// 获取组件名称
        /// </summary>
        /// <param name="menu"></param>
        /// <returns></returns>
          string GetComponent(SysMenu menu)
        {
            string component = UserConstants.LAYOUT;
            if (!string.IsNullOrEmpty(menu.Component) && !IsMeunFrame(menu))
            {
                component = menu.Component;
            }
            else if (!string.IsNullOrWhiteSpace(menu.Component) && menu.ParentId != 0 && IsInnerLink(menu))
            {
                component = UserConstants.INNER_LINK;
            }
            else if (string.IsNullOrEmpty(menu.Component) && IsParentView(menu))
            {
                component = UserConstants.PARENT_VIEW;
            }
            return component;
        }

        /// <summary>
        /// 是否为菜单内部跳转
        /// </summary>
        /// <param name="menu">菜单信息</param>
        /// <returns></returns>
          bool IsMeunFrame(SysMenu menu)
        {
            return menu.ParentId == 0 && UserConstants.TYPE_MENU.Equals(menu.MenuType)
                && menu.IsFrame.Equals(UserConstants.NO_FRAME);
        }

        /// <summary>
        /// 是否为内链组件
        /// </summary>
        /// <param name="menu">菜单信息</param>
        /// <returns>结果</returns>
          bool IsInnerLink(SysMenu menu)
        {
            return menu.IsFrame.Equals(UserConstants.NO_FRAME) && Tools.IsUrl(menu.Path);
        }

        /// <summary>
        /// 是否为parent_view组件
        /// </summary>
        /// <param name="menu">菜单信息</param>
        /// <returns></returns>
          bool IsParentView(SysMenu menu)
        {
            return menu.ParentId != 0 && UserConstants.TYPE_DIR.Equals(menu.MenuType);
        }

        /// <summary>
        /// 内链域名特殊字符替换
        /// </summary>
        /// <param name = "path" ></ param >
        /// < returns ></ returns >
          string InnerLinkReplaceEach(string path)
        {
            return string.IsNullOrWhiteSpace(path) ? path
                .Replace(UserConstants.HTTP, "")
                .Replace(UserConstants.HTTPS, "")
                .Replace(UserConstants.WWW, "")
                .Replace(".", "/") : path;
        }



    }
}
